package cn.maihe.elg.operation.utils;

import cn.maihe.elg.operation.exception.ErrorCode;
import cn.maihe.elg.operation.exception.SystemRuntimeException;
import cn.maihe.elg.operation.supports.system.ElgResourceService;
import lombok.extern.slf4j.Slf4j;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class DownloadExcelTool {

    /**
     * 导出数据最大记录数
     */
    public static final int maxRowNum = 30000;
    @Autowired
    private ResourceLoader resourceLoader;
    @Value("${spring.profiles.active}")
    private String activeProfile;
    @Resource
    private ElgResourceService elgResourceService;

    public void download(String path, String filename, HttpServletResponse response, List items, Map total) {
        if (items.size() > maxRowNum) {
            throw new SystemRuntimeException(ErrorCode.BSMST004);
        }
        org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:" + path);
        try (InputStream is = resource.getInputStream()) {
            Context context = new Context();
            context.putVar("items", items);
            context.putVar("total", total);
            response.setHeader("Content-type", "application/vnd.ms-excel");
            // 解决导出文件名中文乱码
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            JxlsHelper.getInstance().processTemplate(is, response.getOutputStream(), context);

        } catch (IOException e) {
            e.printStackTrace();
            throw new SystemRuntimeException(ErrorCode.BSMST001);
        } finally {
            try {
                response.getOutputStream().close();
                response.getOutputStream().flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public void downloadByTemplateName(String templateFileName, String downFilename, HttpServletResponse response, List items, Map totalRow) {
        Assert.notNull(templateFileName, "模板文件名不能为空");
        Assert.notNull(downFilename, "保存文件名不能为空");
        Assert.notEmpty(items, "导出数据不能为空");
        if (items.size() > maxRowNum) {
            throw new SystemRuntimeException(ErrorCode.BSMST004);
        }
        Path templatePath = elgResourceService.getExcelTemplatePath(templateFileName);

        try (InputStream is = Files.newInputStream(templatePath)) {
            Context context = new Context();
            context.putVar("items", items);
            context.putVar("total", totalRow);
            response.setHeader("Content-type", "application/vnd.ms-excel");
            // 解决导出文件名中文乱码
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(downFilename.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            JxlsHelper.getInstance().processTemplate(is, response.getOutputStream(), context);
        } catch (IOException e) {
            throw new SystemRuntimeException(ErrorCode.BSMST001);
        } finally {
            try {
                response.getOutputStream().close();
                response.getOutputStream().flush();
            } catch (IOException e) {
                log.error("关闭输出流异常：{}", e.getMessage(), e);
            }

        }
    }
}
